import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'Login',
    meta: {
      title: '登陆'
    },
    component: () => import(/* webpackChunkName: "login" */ '../views/Login/login.vue')
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      title: '首页',
      isShowTabar: true,
      requireAuth: true,
      needKeepAlive: true
    }
  },
  {
    path: '/about',
    name: 'About',
    meta: {
      title: '关于',
      isShowTabar: true,
      requireAuth: true
    },
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path: '/error',
    name: 'Error',
    meta: {
      title: '错误'
    },
    component: () => import(/* webpackChunkName: "error" */ '../views/ErrorPage.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const isAuthenticated = sessionStorage.getItem('token')
  const title = to.meta && to.meta.title
  // 设置标题
  if (title) {
    document.title = title
  }

  if (to.meta.requireAuth) {
    if (isAuthenticated) {
      next()
    } else {
      next({ name: 'Login' })
    }
  } else {
    if (isAuthenticated && to.name === 'Login') {
      next({ name: 'Home' })
    } else {
      next()
    }
  }

  // 不存在路由时
  if (to.matched.length === 0) {
    next({ name: 'Error' })
  } else {
    next()
  }
})

export default router
